﻿using System;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;

namespace Crossroad.Utils.Extensions
{
    /// <summary>
    /// 字符串验证
    /// </summary>
    public static class ValidateExt
    {
        [Description("电子邮箱")]
        public readonly static Regex Email = new Regex("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$");
        [Description("电子邮箱 验证")]
        public static bool ValidateEmail(this string input)
        {
            return Email.IsMatch(input);
        }

        [Description("手机号")]
        public readonly static Regex Phone = new Regex("^1[0-9]{10}$");
        [Description("手机号 验证")]
        public static bool ValidatePhone(this string input)
        {
            return Phone.IsMatch(input);
        }
        [Description("手机号 检查")]
        public static void CheckPhone(this string input)
        {
            if(!ValidatePhone(input))
                throw new Exception("手机号格式错误");
        }

        [Description("固话号码")]
        public readonly static Regex Telephone = new Regex("^([0-9]{3,4}-)?[0-9]{7,8}$");
        [Description("固话号码 验证")]
        public static bool ValidateTelephone(this string input)
        {
            return Telephone.IsMatch(input);
        }

         [Description("验证任意字符指定长度")]
        public static bool ValidateCharacter(this string input, int minLength, int maxLength)
        {
            var str = new StringBuilder("^.{");
            str.Append(minLength);
            str.Append(",");
            str.Append(maxLength);
            str.Append("}$");

            return new Regex(str.ToString()).IsMatch(input);
        }

        [Description("验证任意字符指定长度 默认0-32")]
        public static bool ValidateCharacter(this string input, int maxLength = 32)
        {
            return ValidateCharacter(input, 0, maxLength);
        }

         [Description("检查任意字符指定长度")]
        public static void CheckCharacter(this string input, int minLength, int maxLength, string errMsg = "")
        {
            if(!ValidateCharacter(input, minLength, maxLength))
                throw new Exception($"{errMsg} 格式错误");
        }

        [Description("检查任意字符指定长度 默认0-32")]
        public static void CheckCharacter(this string input, int maxLength = 32, string errMsg = "")
        {
            CheckCharacter(input, 0, maxLength, errMsg);
        }

        [Description("检查数值是否超出指定范围")]
        public static void CheckDecimal(this decimal input, decimal min, decimal max, string errMsg = "")
        {
            if (!(input >= min && input <= max))
                throw new Exception($"{errMsg} 格式错误");
        }

        [Description("检查数值 不得小于等于0")]
        public static void CheckEmpty(this decimal input, string errMsg = "")
        {
            if (input <= 0)
                throw new Exception($"{errMsg} 不得小于等于0");
        }


    }
}
